//
//  RHAuthCodeViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/19.
//

#import "RHAuthCodeViewController.h"
#import "NSAttributedString+YYText.h"
#import "YYLabel.h"
#import "BaseModel.h"
@interface RHAuthCodeViewController ()<QMUITextFieldDelegate>
@property (nonatomic ,strong)NSMutableArray *TFArr;

@property(nonatomic ,strong)NSMutableString *codeStr;

@property(nonatomic,strong)YYLabel *contentL;

@property (nonatomic ,strong) QMUIButton *vertifyBtn;

@property (nonatomic, strong) QMUILabel *timeLab;

@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic ,assign) NSInteger count;

@property (nonatomic ,strong) QMUIButton *errorBtn;
@end

@implementation RHAuthCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupUI];
    [self checkAllTextField];
    [self startCountingTimer];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(NSMutableString*)codeStr
{
    NSMutableString *code = [NSMutableString string];
    for (QMUITextField *tf in self.TFArr) {
        if(tf.text.length>0) [code appendString:tf.text];
    }
    if(code.length>0) return code;
    return @"".mutableCopy;
}
-(void)setUserInfo:(NSMutableDictionary *)userInfo
{
    _userInfo = userInfo;
}
- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    UIImageView *imageV = [[UIImageView alloc] init];
    [imageV setImage:[UIImage imageNamed:@"vertifyCode_icon"]];
    [self.view addSubview:imageV];
    
    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(86, 97));
        make.top.mas_offset(kSafe_top+20);
        make.centerX.mas_offset(0);
    }];
    
    
    
    QMUILabel *titleLab = [[QMUILabel alloc] init];
    [titleLab setText:@"请输入6位验证码".rh_localized];
    [titleLab setTextAlignment:NSTextAlignmentCenter];
    [titleLab setFont:[UIFont systemFontOfSize:18]];
    [self.view addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
        make.top.equalTo(imageV.mas_bottom).offset(20);
    }];
    
    
    
    YYLabel *contentL = [[YYLabel alloc] init];
    self.contentL = contentL;
    NSString *str = [NSString stringWithFormat:@"%@ %@",@"验证码已发送至".rh_localized,self.userInfo[@"email"]];
    //设置多行
    contentL.numberOfLines = 0;
    //这个属性必须设置，多行才有效
    contentL.preferredMaxLayoutWidth = SCREEN_WIDTH-30;
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
    attri.yy_lineSpacing = 8;
    attri.yy_alignment = NSTextAlignmentCenter;
    attri.yy_font = [UIFont systemFontOfSize:13];
    //FontColor(@"#3ECE80")
    attri.yy_color = [UIColor colorWithHexString:@"#666666"];
    
    NSRange range1 = [str rangeOfString:self.userInfo[@"email"]];

    [attri yy_setTextHighlightRange:range1 color:CMainColorGreen backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
    }];
    
    //用label的attributedText属性来使用富文本
    contentL.attributedText = attri;
    CGSize maxSize = CGSizeMake(SCREEN_WIDTH-30, MAXFLOAT);
    //计算文本尺寸
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
    contentL.textLayout = layout;
    //CGFloat introHeight = layout.textBoundingSize.height;
    
    [self.view addSubview:contentL];
    
    [contentL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
        make.top.equalTo(titleLab.mas_bottom).offset(5);
    }];
    
    
    UIView *bgView = [[UIView alloc] init];
    [bgView setBackgroundColor:UIColor.clearColor];
    [self.view addSubview:bgView];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(50);
        make.right.mas_offset(-50);
        make.top.equalTo(contentL.mas_bottom).offset(25);
        make.height.mas_equalTo(40);
    }];
    
    kWeakSelf;
    self.TFArr = [[NSMutableArray alloc]init];
    NSArray *array = @[@"",@"",@"",@"",@"",@""];
    NSMutableArray *views = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *textField_bg = [[UIView alloc] init];
        [textField_bg.layer setCornerRadius:5];
        textField_bg.layer.borderColor = kCOLOR_HEX(@"#CDD0D6").CGColor;
        textField_bg.layer.borderWidth = 1;
        [textField_bg setBackgroundColor:kCOLOR_HEX(@"#F4F6F9")];
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setTextColor:CMainColorGreen];
        [textField setFont:[UIFont boldSystemFontOfSize:22]];
        [textField setTextAlignment:NSTextAlignmentCenter];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField_bg addSubview:textField];
        [weakSelf.TFArr addObject:textField];
        textField.tag = idx;
        textField.delegate = self;
        
        [bgView addSubview:textField_bg];
        [views addObject:textField_bg];
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
        }];
    }];
    
    [views mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.centerY.mas_offset(0);
    }];
    
    [views mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:40 leadSpacing:0 tailSpacing:0];
    
    
    
    _errorBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_errorBtn setTitle:@"验证码错误".rh_localized forState:UIControlStateNormal];
    [_errorBtn setTitleColor:kCOLOR_HEX(@"#FF5219") forState:UIControlStateNormal];
    [_errorBtn.titleLabel setFont:[UIFont systemFontOfSize:10]];
    [_errorBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [self.view addSubview:_errorBtn];
    _errorBtn.hidden = YES;
    [_errorBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(52);
        make.top.equalTo(bgView.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(150, 30));
    }];
    
    
    
    QMUIButton *verifyBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [verifyBtn setTitle:@"校验".rh_localized forState:UIControlStateNormal];
    [verifyBtn setBackgroundColor:CMainColorGreen];
    [verifyBtn.layer setCornerRadius:5];
    [verifyBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [verifyBtn setTitleColor:kCOLOR_HEX(@"#171A1D") forState:UIControlStateDisabled];
   
    [verifyBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [self.view addSubview:verifyBtn];
    self.vertifyBtn = verifyBtn;
    
    [verifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.top.equalTo(bgView.mas_bottom).offset(100);
    }];
    
    _timeLab = [[QMUILabel alloc]init];
    _timeLab.textColor = CMainColorGreen;
    _timeLab.font = kSYSTEMFONT(16);
    _timeLab.text = @"00:59";
    [self.view addSubview:_timeLab];
    _timeLab.hidden = YES;
    [_timeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(verifyBtn.mas_bottom).offset(25);
    }];
    
    
    YYLabel *reSendLab = [[YYLabel alloc] init];
    [self.view addSubview:reSendLab];
    NSString *reSendStr = @"没有收到验证码？重新发送".rh_localized;
    //设置多行
    reSendLab.numberOfLines = 0;
    //这个属性必须设置，多行才有效
    reSendLab.preferredMaxLayoutWidth = SCREEN_WIDTH-30;
    NSMutableAttributedString *reSend_attri = [[NSMutableAttributedString alloc] initWithString:reSendStr];
    reSend_attri.yy_lineSpacing = 8;
    reSend_attri.yy_alignment = NSTextAlignmentCenter;
    reSend_attri.yy_font = [UIFont systemFontOfSize:13];
    //FontColor(@"#3ECE80")
    reSend_attri.yy_color = [UIColor colorWithHexString:@"#666666"];
    NSRange range_send = [reSendStr rangeOfString:@"重新发送".rh_localized];

    [reSend_attri yy_setTextHighlightRange:range_send color:CMainColorGreen backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        if (weakSelf.count == 0) {
            [weakSelf getVertifyCode];
        }
    }];
    
    //用label的attributedText属性来使用富文本
    reSendLab.attributedText = reSend_attri;
    CGSize maxSize_resend = CGSizeMake(SCREEN_WIDTH-30, MAXFLOAT);
    //计算文本尺寸
    YYTextLayout *layout_resend = [YYTextLayout layoutWithContainerSize:maxSize_resend text:reSend_attri];
    reSendLab.textLayout = layout_resend;
    //CGFloat introHeight = layout.textBoundingSize.height;
    
    [self.view addSubview:reSendLab];
    
    [reSendLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(20);
        make.top.equalTo(weakSelf.timeLab.mas_bottom).offset(5);
    }];
    
    
    QMUIButton *backBtn = [[QMUIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.mas_offset(8);
        make.top.mas_offset(kSafe_top);
    }];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    

    [[verifyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
       
        [weakSelf registerAction];
    }];
}

#pragma mark ----        //获取验证码 参数
-(void)getVertifyCode
{
        NSDictionary *para = @{@"sendEmail":self.userInfo[@"email"],@"action":@"新用户注册,获取验证码"};
        [QMUITips showLoading:@"获取验证码".rh_localized inView:self.view];
        [BaseModel startWithCompletionAPIKey:H_sendCodeNoToken header:@{} argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"验证码已发送".rh_localized];
                [self startCountingTimer];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        }];
}

#pragma mark ----- 校验 -----
-(void)registerAction
{
    if(self.codeStr.length==0){
        [QMUITips showError:@"请输入验证码".rh_localized];
        return;
    }
    [self.userInfo setValue:self.codeStr forKey:@"recode"];
    [QMUITips showLoading:@"注册中...".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_register argument:self.userInfo requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-3] animated:YES];
            [QMUITips showSucceed:@"注册成功".rh_localized];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"UserRegisterSuccess" object:self.userInfo];
        }else if(resultModel.code == 60037){
            [self showErrorVeritifyCode];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)startCountingTimer
{
    self.count = 59;
    self.timeLab.hidden = NO;
    self.timeLab.text = @"00:59";
    if (self.timer == nil) {
        self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

-(void)timeCounting
{
    if (self.count == 0) {
        [self.timer invalidate];
        self.timer = nil;
    }else{
        self.count --;
        self.timeLab.text = [NSString stringWithFormat:@"%02ld:%02ld",self.count/60,self.count%60];
    }
}

-(void)checkAllTextField
{
    self.vertifyBtn.enabled = self.codeStr.length == 6;
    self.vertifyBtn.backgroundColor = (self.codeStr.length == 6)?CMainColorGreen:kCOLOR_HEX_A(@"#000000", 0.24);
}

-(void)showErrorVeritifyCode
{
    for (QMUITextField *tf in self.TFArr) {
        UIView *bgView = tf.superview;
        bgView.layer.borderColor = kCOLOR_HEX(@"#FF5219").CGColor;
        bgView.layer.borderWidth = 1;
    }
    self.errorBtn.hidden = NO;
}

-(void)clearErrorVeritifyCode
{
    for (QMUITextField *tf in self.TFArr) {
        UIView *bgView = tf.superview;
        bgView.layer.borderColor = kCOLOR_HEX(@"#ffffff").CGColor;
        bgView.layer.borderWidth = 0;
    }
    self.errorBtn.hidden = YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self checkAllTextField];
}


//自动填充粘贴板的内容
-(void)appBecomActive
{
    NSString *codeStr = [UIPasteboard generalPasteboard].string;
    NSString *reg = @"[0-9]{6}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];
    BOOL isSixNumber = [predicate evaluateWithObject:codeStr];
    if(isSixNumber){
        [self.TFArr enumerateObjectsUsingBlock:^(QMUITextField *tf, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *temp = [codeStr substringWithRange:NSMakeRange(idx, 1)];
            tf.text = temp;
        }];
    }
    NSLog(@"---->粘贴板的内容:%@",codeStr);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //删除
    if([string isEqualToString:@""]){
        [self clearErrorVeritifyCode];
        //光标跳到左边那一个
        if (textField.text.length == 1) {
            if (textField.tag != 0) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    QMUITextField *textF = (QMUITextField*)self.TFArr[textField.tag-1];
                    [textF becomeFirstResponder];
                });
            }
        }
        return YES;
    }else{
        //输入
        //已经有数字,切换为下一个textField为响应者
        if(textField.text.length>0){
            if(textField.tag+1 <self.TFArr.count){
                QMUITextField *textF =  (QMUITextField*)self.TFArr[textField.tag+1];
                textF.text = string;
                [textF becomeFirstResponder];
                if(textField.tag == self.TFArr.count-2){
                    [textF resignFirstResponder];
                }
                return NO;
            }else{
                //输完了
                [textField resignFirstResponder];
            }
            return YES;
        }else{
            //没数字
            return YES;
        }
    }
    
    
    
    
    return YES;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
